<template>
  <div class="app">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色设置</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <el-card class="box-card">
      <div>
        <el-input
          style="width:240px;margin-right:30px"
          placeholder="请输入角色名称"
          v-model="condition.roleName"
          clearable
        >
        </el-input>

        <el-select
          class="adStatus"
          v-model="condition.roleStatus"
          clearable
          placeholder="请选择角色状态"
        >
          <el-option key="0" label="冻结" value="0"> </el-option>
          <el-option key="1" label="正常" value="1"> </el-option>
        </el-select>
        <el-button
          style="margin-left:30px"
          type="primary"
          @click="searchMenuName"
          class="my-el-button el-icon-search"
          >查询</el-button
        >
        <el-button
          class="addRole el-icon-plus"
          size="small"
          @click="addRole"
          type="success"
          >添加角色</el-button
        >
      </div>
      <!-- table 展示角色 信息 开始 -->
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色状态" prop="roleStatus">
          <template slot-scope="scope">
            <el-tag :type="scope.row.roleStatus == 1 ? 'success' : 'danger'">{{
              scope.row.roleStatus == 1 ? '正常' : '冻结'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              class="my-el-button-default"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              :disabled="scope.row.roleStatus == 1"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="success"
              class="el-icon-plus"
              @click="handleAddMenu(scope.$index, scope.row)"
              >添加权限菜单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- table 展示角色 信息 结束 -->
      <!-- 分页 开始-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="condition.page"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="condition.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 分页 结束-->
    </el-card>
    <!-- 添加 与 修改 角色 弹出框  开始 -->
    <el-dialog
      :title="flag == 1 ? '添加角色' : '修改角色'"
      :visible.sync="dialogFormVisible"
      v-loading.fullscreen.lock="fullscreenLoading"
    >
      <el-form :rules="rules" ref="roleForm" :model="roleForm">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          v-if="flag != 1"
          label="角色状态"
          :label-width="formLabelWidth"
        >
          <el-dropdown @command="changeStatus">
            <el-button :type="roleForm.roleStatus == 1 ? 'success' : 'danger'">
              {{ roleForm.roleStatus == 1 ? '正常' : '冻结' }}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="calculation(1, roleForm)"
                >正常</el-dropdown-item
              >
              <el-dropdown-item :command="calculation(0, roleForm)"
                >冻结</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="my-el-button-default"
          @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button class="my-el-button" type="primary" @click="determine"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加 与 修改 角色 弹出框  结束 -->
    <!-- 菜单 弹出框开始 -->
    <el-dialog
      :title="`为 （${selectItem.roleName}） 角色添加菜单权限`"
      :visible.sync="dialogTableVisible"
    >
      <el-table
        ref="multipleTable"
        v-loading="menuTableloading"
        :data="menuTableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @select="select"
      >
        >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="drag-item-title ">
              <el-row>
                <el-col class="line" :span="4">
                  二级菜单名
                </el-col>
                <el-col class="line" :span="4">
                  二级菜单url
                </el-col>
                <el-col class="line" :span="4">
                  二级菜单图标
                </el-col>
              </el-row>
            </div>
            <div
              v-for="item in props.row.menuList"
              :key="item._id"
              class="drag-item  text item"
            >
              <el-row>
                <el-col class="line" :span="4"
                  >&nbsp;{{ item.menuName }}</el-col
                >
                <el-col class="line" :span="4">/{{ item.menuUrl }}</el-col>
                <el-col class="line" :span="4">
                  <img
                    style="width:20px;height:20px"
                    class="icon"
                    :src="item.menuIcon"
                  />
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="菜单名称" prop="menuName"> </el-table-column>
        <el-table-column label="菜单url" prop="">
          <template slot-scope="scope"> /{{ scope.row.menuUrl }} </template>
        </el-table-column>
        <el-table-column label="菜单图标" prop="">
          <template slot-scope="scope">
            <img style="width:20px;height:20px" :src="scope.row.menuIcon" />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="my-el-button-default"
          :disabled="menuTableloading"
          @click="dialogTableVisible = false"
          >取 消</el-button
        >
        <el-button
          class="my-el-button"
          type="primary"
          :disabled="menuTableloading"
          @click="determineUpdateMenu"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 菜单 弹出框 结束 -->
  </div>
</template>
<script>
import {
  queryRole,
  addRole,
  updateRoleById,
  removeRoleById,
  queryMenuList,
  removeRoleMenuById,
  addRoleMenu,
  queryRoleMenu,
  queryRoleTotal
} from '@/network/authorityManager'
// import { queryMenu } from '@/network/index'
export default {
  data() {
    return {
      // 查询条件
      condition: {
        page: 1,
        size: 10,
        roleStatus: '',
        roleName: ''
      },
      // 角色数据
      tableData: [],
      loading: false,
      // 添加 或 修改标记  1添加  2修改
      flag: -1,
      roleForm: {
        _id: '',
        roleName: '',
        roleStatus: 1
      },
      formLabelWidth: '120px',
      // 弹层显示 隐藏
      dialogFormVisible: false,
      // 验证规则
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 选中的下标
      selectIndex: -1,
      // 选中的角色对象
      selectItem: {},
      // 添加菜单 权限 弹窗
      dialogTableVisible: false,
      // 所有菜单table
      menuTableData: [],
      // 菜单表格 加载
      menuTableloading: false,
      // 当前用户的 菜单列表
      menuList: [],
      // 杯子 菜单列表
      cupMenuList: [],
      user: {},
      // 角色总数
      total: 10,
      fullscreenLoading: false
    }
  },
  methods: {
    // 查询所有角色
    queryRole() {
      this.loading = true
      queryRole(this.condition).then(res => {
        this.tableData = []
        for (let rs in res.data) {
          this.tableData.push(JSON.parse(res.data[rs]))
        }
        this.loading = false
      })
      queryRoleTotal(this.condition).then(res => {
        this.total = res.count
        console.info(res)
      })
    },
    // 添加 角色
    addRole() {
      this.flag = 1
      this.roleForm = {
        _id: '',
        roleName: '',
        roleStatus: 1
      }
      this.dialogFormVisible = true
    },
    // 编辑按钮
    handleEdit(index, row) {
      this.selectIndex = index
      this.roleForm = JSON.parse(JSON.stringify(row))
      this.flag = 2
      this.dialogFormVisible = true
      console.info(row)
    },
    // 修改角色状态
    changeStatus(row) {
      row.item.roleStatus = row.status
    },
    // 计算属性
    calculation(status, item) {
      return {
        status,
        item
      }
    },
    // 确定按钮
    determine() {
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          if (this.flag == 1) {
            // 添加 角色
            this.fullscreenLoading = true
            addRole(this.roleForm).then(res => {
              this.roleForm._id = res.id_list[0]
              if (this.tableData.length < this.condition.size) {
                this.tableData.push(this.roleForm)
              }
              this.$message.success('添加成功')
              this.dialogFormVisible = false
              this.fullscreenLoading = false
            })
            return
          }
          this.$confirm('此操作将永久修改该信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.fullscreenLoading = true
              this.$message.success('修改成功')
              updateRoleById(this.roleForm)
              this.tableData.splice(this.selectIndex, 1, this.roleForm)
              this.dialogFormVisible = false
              this.fullscreenLoading = false
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              })
            })
        }
      })
    },
    // 重置表单
    reset() {
      this.roleForm = {
        _id: '',
        roleName: '',
        roleStatus: 1
      }
      this.selectIndex = -1
    },
    // 删除角色
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableData.splice(index, 1)
          removeRoleById(row._id)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取 菜单列表
    async queryMenuList() {
      this.menuTableloading = true
      // 角色 菜单置空
      this.menuList = []
      // 全部菜单 置空
      this.menuTableData = []
      // 查询角色的 菜单列表
      let res = await queryRoleMenu(this.selectItem._id)

      for (let rs in res.data) {
        this.menuList.push(JSON.parse(res.data[rs]))
      }
      console.info(this.menuList)
      // 查询 所有菜单
      queryMenuList({ page: 1, size: 1000 }).then(res => {
        this.menuTableData = JSON.parse(res.resp_data).list
        this.$nextTick(() => {
          for (let rs in this.menuTableData) {
            for (let cup in this.menuList) {
              if (this.menuTableData[rs]._id == this.menuList[cup].menuId) {
                this.menuTableData[rs].flag = true
                this.$refs.multipleTable.toggleRowSelection(
                  this.menuTableData[rs],
                  true
                )
                this.cupMenuList.splice(cup, 1)
                break
              }
            }
          }
        })

        console.info(this.menuTableData)
        this.menuTableloading = false
      })
    },
    // 添加菜单权限方法
    handleAddMenu(index, row) {
      this.selectIndex = index
      this.selectItem = row
      this.queryMenuList()
      this.dialogTableVisible = true
      console.info(row)
    },
    handleSelectionChange(value) {
      for (let i in this.menuTableData) {
        this.menuTableData[i].flag = false
      }
      for (let i in value) {
        value[i].flag = true
      }
      console.info(value)
    },
    // 选择时 触发
    select(selection, row) {
      console.info(selection)
      // row.flag = !row.flag
      console.info(row)
    },
    // 确定按钮
    async determineUpdateMenu() {
      this.menuTableloading = true
      console.info(this.menuTableData)
      var arr = this.menuTableData.filter(item => {
        return item.flag
      })
      let newRoleMent = []
      for (let i in arr) {
        newRoleMent.push({ menuId: arr[i]._id, roleId: this.selectItem._id })
      }
      console.info(JSON.stringify(newRoleMent))

      await removeRoleMenuById(this.selectItem._id)
      addRoleMenu(JSON.stringify(newRoleMent))
      if (this.selectItem._id == this.role._id) {
        sessionStorage.removeItem('menuList')
      }
      this.dialogTableVisible = false
      this.menuTableloading = false
      this.$message.success('修改成功')
      console.info(this.selectItem)
      console.info(arr)
    },
    // size数据改变
    handleSizeChange(val) {
      this.condition.size = val
    },
    // 翻页
    handleCurrentChange(val) {
      this.condition.page = val
    },
    // 搜索按钮
    searchMenuName() {
      this.queryRole()
    }
  },
  // 生命周期函数
  mounted() {
    this.queryRole()
    this.user = JSON.parse(sessionStorage.getItem('user'))
    this.role = JSON.parse(sessionStorage.getItem('role'))
  },
  // 监听属性
  watch: {
    'condition.page': {
      // 页码发生变化
      handler: function() {
        this.queryRole()
      }
    },
    'condition.size': {
      // 每页多少条发生变化
      handler: function() {
        this.queryRole()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.addRole {
  float: right;
}
.addRole::after {
  content: '';
  display: inline-block;
  clear: both;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.drag-item {
  padding-top: 7px;
  border-top: 1px solid rgb(226, 223, 223);
}
.drag-item:last-child {
  border-bottom: 1px solid rgb(226, 223, 223);
}
.drag-item-title {
  border-top: none;
  padding-bottom: 10px;
}
.box-card {
  margin-top: 20px;
}
.el-col-6 {
  width: 200px;
  height: 100%;
}
.chapterBody {
  margin: 10px 10px;
}
.drag-item-title {
  color: #67c23a;
}
.el-checkbox > .is-checked > span {
  background-color: #fd7c27;
  border-color: #fd7c27;
}
.cell > label > span > span {
  background-color: #fd7c27;
  border-color: #fd7c27;
}
</style>
